{{ define "content" }}
<article class="fbox">
  <header class="entry-header">
  </header>
  <div class="ui segment">
    <div class="field">
      <label for="output">智能闲聊机器人：</label>
      <textarea id="outputchat" class="form-control" rows="10" readonly=""></textarea>
    </div>
    <div class="header-widget field">
      <label for="output">输入问题：</label>
      <input type="text" id="inputchat" class="search-field form-control" placeholder="在此输入问题，回车后发送"
        onkeydown='if(event.keyCode==13){sendChat();}'></input>
    </div>
  </div>
</article>
{{ end }}
{{ define "extend_script" }}
<script>
  $ = jQuery

  function throttle(callback, limit) {
    var waiting = false; // Initially, we're not waiting
    return function () { // We return a throttled function
      if (!waiting) { // If we're not waiting
        callback.apply(this, arguments); // Execute users function
        waiting = true; // Prevent future invocations
        setTimeout(function () { // After a period of time
          waiting = false; // And allow future invocations
        }, limit);
      }
    }
  }

  function StringTrim(x) {
    return x.replace(/^\s+|\s+$/gm, '');
  }

  function submitChatText(text) {
    StringTrim(text);
    if (text.length == 0) {
      console.log("aichat text is empty")
      return;
    }
    console.log('send chat:', text);
    $.ajax({
      type: 'GET',
      url: '/aichat/question?text=' + encodeURIComponent(text),
      success: result => {
        if (result) {
          var outputChat = $('#outputchat');
          var content = outputChat.val();
          if (content.length > 1024) {
            content = content.substring(content.length / 2)
          }
          outputChat.val(content + "● " + result.msg + "\r\n");
          outputChat.scrollTop(outputChat[0].scrollHeight);
        }
      },
    });
  }

  submitChatTextThrottle = throttle(submitChatText, 1000)

  function sendChat() {
    var text = $('#inputchat').val();
    $('#inputchat').val('');
    submitChatTextThrottle(text);
  }
</script>
{{ end }}